<?php

namespace app\admin\controller\coupon;

use app\common\controller\Backend;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Coupon extends Backend
{

    /**
     * Coupon模型对象
     * @var \app\admin\model\Coupon
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Coupon;

    }

    /**
     * 查看
     */
    // public function index()
    // {
    //     if ($this->request->isAjax())
    //     {
    //         list($where, $sort, $order, $offset, $limit) = $this->buildparams();
    //         $total = $this->model
    //                 ->where($where)
    //                 ->order($sort, $order)
    //                 ->count();
    //         $list = $this->model
    //                 ->alias('c')
    //                 ->join('__USER__ u','c.uid = u.id', 'LEFT JOIN')
    //                 ->where($where)
    //                 ->order($sort, $order)
    //                 ->limit($offset, $limit)
    //                 ->select();
    //         $result = array("total" => $total, "rows" => $list);
    //
    //         return json($result);
    //     }
    //     return $this->view->fetch();
    // }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    for ($i=0; $i < $params['num']; $i++) {
                        $data[] = [
                            'price' => $params['price'],
                            'code'  => generate_code()
                        ];
                    }
                    $result = $this->model->allowField(true)->saveAll($data);

                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


}
